package com.y.mytest.collection.list;

import com.y.mytest.collection.stream.Student;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collectors;

import static java.util.stream.Collectors.collectingAndThen;
import static java.util.stream.Collectors.toCollection;

/**
 * @ClassName ListDistinct
 * @Description
 * @Author YeZiHao
 * @Date 2022/9/7 15:41
 **/
public class ListDistinct {
    public static void main(String[] args) {
        List<Student> students = new ArrayList<>(16);
        students.add(new Student("1", "张三", 18, "male", 88));
        students.add(new Student("1", "李四", 17, "male", 60));
        students.add(new Student("2", "王五", 18, "male", 100));

        ArrayList<Student> collect = students.stream().collect(collectingAndThen(
                toCollection(() -> new TreeSet<>(Comparator.comparing(Student::getId))), ArrayList::new));
        System.out.println(collect);

        System.out.println(students.stream().map(Student::getId).collect(Collectors.joining(",")));

        System.out.println(distinct(students, Student::getId));
    }

    public static <T> Predicate<T> distinctByKey(Function<? super T, ?> key) {
        Set<Object> seen = ConcurrentHashMap.newKeySet();
        return t -> seen.add(key.apply(t));
    }

    public static <T> List<T> distinct(List<T> list, Function<? super T, ?> key) {
        return list.stream().filter(distinctByKey(key)).collect(Collectors.toList());
    }
}
